package com.edu.zut.controller;


import cn.hutool.core.io.FileUtil;
import com.edu.zut.entity.Result;
import com.edu.zut.mapper.ResultMapper;
import com.edu.zut.mapper.UserMapper;
import com.edu.zut.result.HttpCode;
import com.edu.zut.result.ResponseResult;
import com.edu.zut.service.PaperService;
import com.edu.zut.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * 学生论文表 前端控制器
 * </p>
 *
 * @author 许文科
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/api/paper")
public class PaperController {

    @Value("${detectApplication}")
    private String command;
    @Value("${resultPath}")
    private String resultPath;


    @Resource
    private PaperService paperService;

    @Resource
    private UserMapper userMapper;
    @Resource
    private ResultMapper resultMapper;
    @Resource
    private QiniuUtil qiniuUtil;


    @PostMapping("/upload")
    @PreAuthorize("hasAnyRole('student','teacher','admin')")
    public ResponseResult upload(@RequestParam("file") MultipartFile file) {
        return paperService.uploadPaper(file);
    }

    /**
     * 检测功能
     *
     * @param paperPath
     * @return
     */
    @PostMapping("/detect")
    @PreAuthorize("hasAnyRole('student','teacher','admin')")
    public ResponseResult detect(@PathParam("paperPath") String paperPath) {

        //UUID作为检测报告名称，更改后的文件名
        String name = UUID.randomUUID().toString().replace("-", "");

        String[] cmd = {"D:\\corc++\\paperdetect\\paperdetect\\bin\\Debug\\paperdetect.exe", paperPath, name};
        Process process;

        try {
            //Runtime.getRuntime().exec用于调用外部可执行程序或系统命令，并重定向外部程序的标准输入、标准输出和标准错误到缓冲池。
            process = Runtime.getRuntime().exec(cmd);
            //等待cmd子进程完成再往下执行
            process.waitFor();//阻塞当前线程，并等待外部程序中止后获取结果码

            //获取用户信息
            String username = (String) SecurityContextHolder
                    .getContext().getAuthentication().getPrincipal();
            Long userId = userMapper.getUserIdByUserName(username);
            Result result = new Result();

            //生成文件后缀
            String resultName = name + ".txt";
            result.setResultName(name);

            //将检测报告上传到七牛云，获得url，并保存到数据库中
//            String tranfer = new TxtToPDF().tranfer(resultPath,name);
            byte[] bytes = FileUtil.readBytes(resultPath + "//" + resultName);
            String path = qiniuUtil.uploadBybyte(bytes, resultName);

            result.setPath(path);
            result.setUserId(userId);

            //将检测报告插入到数据库
            resultMapper.insert(result);

            return new ResponseResult(HttpCode.SUCCESS, "检测成功", resultPath + "\\" + resultName);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return new ResponseResult(HttpCode.SUCCESS, "失败", null);
    }

}
